package nayasis.common.db.manager.sql;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nayasis.common.Const;
import nayasis.common.util.FileUtil;
import nayasis.common.xml.XmlBuilder;

import org.jdom2.Element;
import org.jdom2.JDOMException;

public abstract class SqlManager {

	private static Map<String, SqlMap> sqlPool = new HashMap<>();

	static {
		
		try {
			loadSql();
		} catch (IOException | JDOMException e) {
			e.printStackTrace();
		}
		
	}

	private static void loadSql() throws IOException, JDOMException {
		
		List<Path> fileList = FileUtil.getList( Const.path.sql, true, false, -1, "*.xml" );
		
		int rootPathNameCount = Paths.get( Const.path.sql ).getNameCount();
		
		for( Path path : fileList ) {
			
			XmlBuilder xmlBuilder = new XmlBuilder( path.toString() );

			List<Element> elements = xmlBuilder.getElements( "/sqlList/sql" );
			
			if( elements.size() == 0 ) continue;
			
			String xmlPath = path.subpath( rootPathNameCount, path.getNameCount() ).toString().replaceFirst( ".xml", "" ).replaceAll( "\\\\", "/" );
			
			for( Element element : elements ) {
				
				String name = element.getAttributeValue( "name" );

				if( name == null ) continue;
				
				SqlMap map = new SqlMap();
				
				map.setSql( element.getValue() );
				map.setDbSpec( element.getAttributeValue("dbSpec") );
				
				sqlPool.put( String.format("/%s/%s", xmlPath, name), map );
				
			}
			
		}

	}
	
	public static SqlMap getSql( String path, String dbSpec ) {
		
		SqlMap map = sqlPool.get( path );
		
		if( map == null ) {
			map = new SqlMap();
			map.setSql( path );
		}
		
		return map;
		
	}
	
}
